package dd.prog2.exercises.set14;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class ImagePanel extends JPanel {

	private BufferedImage image = null;
	private PhotoViewer pv;

	public ImagePanel(PhotoViewer pv) {
		this.pv = pv;
		this.setBackground(Color.BLACK);

	}

	public void setImage(File file){
		try {
			image = ImageIO.read(file);
		} catch (IOException io) {
			// handle exception...
			System.err.println("IOException while reading image");
			io.printStackTrace();
		}
	}
	
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if(image != null){
			double scaleFactor = Math.max(image.getWidth()/(pv.getWidth()*1.0), image.getHeight()/(pv.getHeight()*1.0));		
			this.setSize(pv.getSize());
			g.drawImage(image.getScaledInstance((int)(image.getWidth()/scaleFactor), (int)(image.getHeight()/scaleFactor), 1), 0, 0, pv);
		}
	}

}